<template>
  <div>
    <div class="access-header">
      <div></div>
      <div>
        <el-button type="primary" @click="addRow">新增</el-button>
      </div>
    </div>
    <div class="access-panel">
      <div class="tree-container">
        <el-tree
          ref="treeRef"
          :data="treeData"
          :props="defaultProps"
          node-key="id"
          default-expand-all
          auto-expand-parent
          highlight-current
          :expand-on-click-node="false"
          @node-click="handleNodeClick"
        />
      </div>
      <div class="table-container">
        <el-table
          :data="tableData"
          style="width: 100%"
          :row-class-name="tableRowClassName"
        >
          <el-table-column prop="module_name" label="菜单" />
          <el-table-column prop="url" label="路径" />
          <!-- <el-table-column prop="type" label="类型" /> -->
          <el-table-column prop="created_at" label="创建时间" />
          <el-table-column prop="updated_at" label="更新时间" />
          <el-table-column fixed="right" label="操作" width="250">
            <template v-slot="scope">
              <el-button
                size="small"
                type="primary"
                @click.stop="editorRow(scope.row)"
              >
                编辑
              </el-button>
              <el-popconfirm
                title="确认要删除该列?"
                confirm-button-text="是"
                cancel-button-text="否"
                @confirm="deleteRow(scope.row)"
              >
                <template #reference>
                  <el-button> 删除 </el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 菜单 -->
    <el-dialog
      v-model="dialogAccessVisible"
      :close-on-click-modal="false"
      destroy-on-close
      :title="dialogAccessTripType == 1 ? '新增' : '编辑'"
    >
      <el-form
        :model="form"
        ref="ruleFormRef"
        :rules="rules"
        label-position="top"
      >
        <el-form-item label="路径" prop="url" label-width="140px">
          <el-input v-model.trim="form.url"></el-input>
        </el-form-item>
        <el-form-item label="名称" prop="module_name" label-width="140px">
          <el-input v-model.trim="form.module_name"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogAccessVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAddAccess"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import request from "utils/request";
import { ElMessage, ElMessageBox } from "element-plus";

export default {
  name: "NestAdminAccess",

  data() {
    return {
      dialogAccessVisible: false,
      dialogAccessTripType: 1,
      form: {
        parentId: null,
        id: "",
        module_name: "",
        url: "",
        created_at: "",
        updated_at: "",
        type: "2",
      },
      defaultProps: {
        children: "children",
        label: "module_name",
      },
      treeData: [],
      tableData: [],
      rules: {
        url: [
          {
            required: true,
            message: "输入框不能为空",
            trigger: "blur",
          },
        ],
        module_name: [
          {
            required: true,
            message: "输入框不能为空",
            trigger: "blur",
          },
        ],
      },
    };
  },

  mounted() {
    this.getAccessList();
  },
  watch: {
    dialogAccessVisible: {
      handler(value) {
        if (!value) {
          Object.assign(this.form, {
            parentId: null,
            id: "",
            module_name: "",
            url: "",
            created_at: "",
            updated_at: "",
            type: "2",
          });
        }
      },
    },
  },
  methods: {
    async getAccessList() {
      let ret = await request.get("/access/list", {
        parentId: this.form.parentId,
      });
      if (ret.code == 200) {
        this.treeData = ret.data || [];
        this.tableData = ret.data || [];
      }
    },
    handleNodeClick(data) {
      let arr = [];
      arr.push(data);
      if (data.children) {
        arr.push(...data.children);
      }
      this.tableData = arr;
      console.log("🚀 ~ file: access.vue:123 ~ data", data);
    },
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex === 1) {
        return "warning-row";
      } else if (rowIndex === 3) {
        return "success-row";
      }
      return "";
    },
    addRow() {
      let key = this.$refs["treeRef"].getCurrentKey();
      this.dialogAccessTripType = 1;
      this.dialogAccessVisible = true;
    },
    async deleteRow(row) {
      let ret = await request.delete(`/access/${row.id}`, {});
      if (ret.code == 200) {
        ElMessage.success("删除成功");
        this.getAccessList();
        this.initMenu();
      }
    },
    editorRow(row) {
      this.dialogAccessTripType = 0;
      Object.assign(this.form, row);
      this.dialogAccessVisible = true;
    },
    async confirmAddAccess() {
      this.$refs["ruleFormRef"].validate(async (valid, fields) => {
        if (valid) {
          let id = this.$refs["treeRef"].getCurrentKey();
          let ret = {};
          if (this.dialogAccessTripType == 1) {
            ret = await request.post("/access/add", {
              id,
              module_name: this.form.module_name,
              url: this.form.url,
            });
          } else {
            ret = await request.patch(`/access/${this.form.id}`, {
              module_name: this.form.module_name,
              url: this.form.url,
            });
          }

          if (ret.code == 200) {
            this.$message({
              message: this.dialogAccessTripType == 1 ? "新增成功" : "编辑成功",
              type: "success",
            });
            this.dialogAccessVisible = false;
            await this.getAccessList();
            this.initMenu();
          } else {
            this.$message({
              message: ret.message,
              type: "error",
            });
          }
        } else {
          console.log("error submit!", fields);
        }
      });
    },
    async initMenu() {
      const accessRoutes = await this.$store.dispatch("permission/getMenus");
      accessRoutes.forEach((route) => {
        this.$router.addRoute("System", route);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.access-header {
  display: flex;
  justify-content: space-between;
  line-height: 60px;
  padding: 0 15px;
}
.access-panel {
  display: flex;
  .tree-container {
    width: 200px;
  }
  .table-container {
    flex: 1;
    padding: 0 15px;
  }
}
.el-table .warning-row {
  --el-table-tr-bg-color: var(--el-color-warning-light-9);
}
.el-table .success-row {
  --el-table-tr-bg-color: var(--el-color-success-light-9);
}
</style>
